<template>
	<div :class="classes">
		<slot></slot>
	</div>
</template>
<script lang="ts">
	import { Prop, Emit, Component, Watch, Mixins } from "vue-property-decorator";
	import Anes from "../base";
	import { findComponentsDownward } from "../../utils/assist";
	import Checkbox from "./checkbox.vue";

	const prefixCls = "ivu-checkbox-group";

	@Component
	export default class CheckboxGroup extends Mixins(Anes) {
		@Prop({ type: Array })
		value!: Array<string | number | boolean>;

		currentValue = this.value;
		childrens = new Array<Checkbox>();
		get classes() {
			return [
				`${prefixCls}`,
				{
					[`ivu-checkbox-${this.size}`]: !!this.size
				}
			];
		}

		mounted() {
			this.updateModel(true);
		}

		public updateModel(update: boolean): void {
			this.childrens = findComponentsDownward<Checkbox>(this, "Checkbox");
			if (
				this.value &&
				this.childrens &&
				this.value.length > 0 &&
				this.childrens.length > 0
			) {
				const { value } = this;
				this.childrens.forEach(child => {
					child.model = value;
					if (update) {
						child.currentValue = value.indexOf(child.label) >= 0;
						child.group = true;
					}
				});
			}
		}
		@Emit()
		change(data: Array<string | number | boolean>) {
			this.currentValue = data;
			this.$emit("input", data);
			this.$emit("on-change", data);
			//	this.dispatch<FormItem>("on-form-change", data);
		}

		@Watch("value")
		onChangeValue() {
			this.updateModel(true);
		}
	}
</script>
